package com.test.vertx.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonObject;

@Service
public class UserService {
	
	private static final String host = "localhost";
	private static final int port = 8080;
	private static HttpClient httpClient = null;
	
	public Future<JsonObject> queryUser(int id) {
		String requestURI = "/users/" + id;
		Future<JsonObject> future = Future.future();
		httpClient.get(port, host, requestURI, response -> {
			if (response.statusCode() == 200) {
				response.bodyHandler(buffer -> {
					future.complete(buffer.toJsonObject());
				});
			}
		}).end();
		return future;
	}
	
	public Future<String> consumer() {
		Vertx vertx = Vertx.vertx();
		httpClient = vertx.createHttpClient(new HttpClientOptions());
		Future<String> futureResult = Future.future();
		@SuppressWarnings("rawtypes")
		List<Future> futures = new ArrayList<>(10000);
		for (int i = 0; i < 5; i++) {
			Future<JsonObject> future = queryUser(i);
			futures.add(future);
		}
		long t1 = System.currentTimeMillis();
		CompositeFuture.all(futures).setHandler(result -> {
			long t2 = System.currentTimeMillis();
			String result1 = "";
			for(Future<JsonObject> future : futures) {
				result1 += future.toString();
			}
			futureResult.complete(result1);
			System.out.println("完成，耗时" + (t2-t1) + "ms");
		});
		return futureResult;
	}

}
